<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row>
				<div class="flex justify-between w-full mb8">
					<el-space>
						<el-popover trigger="click" :width="680" placement="bottom-start">
							<el-form :inline="false" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef" label-width="90px" size="small">
								<el-row>
									<el-col :span="12" class="mb20">
										<el-form-item label="所属单位" prop="deptId">
											<el-tree-select
												v-model="state.queryForm.deptId"
												:data="parentData"
												:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
												clearable
												filterable
												check-strictly
												tag-type="success"
												:render-after-expand="true"
												placeholder="请选择所属单位"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="单位限制" prop="deptLimit">
											<el-select clearable v-model="state.queryForm.deptLimit" :teleported="false">
												<el-option label="本级及子级" :value="10" />
												<el-option label="仅本级" :value="20" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="类型" prop="deviceTypeId">
											<el-select
												v-model="state.queryForm.deviceTypeId"
												clearable
												filterable
												placeholder="请选择设备类型"
												@change="getModelList"
												:teleported="false"
											>
												<el-option
													v-for="item in deviceTypeList"
													:key="item.id"
													:value="item.id"
													:label="item.typeName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="设备型号" prop="deviceModelId">
											<el-select
												v-model="state.queryForm.deviceModelId"
												clearable
												filterable
												placeholder="请选择设备型号"
												:teleported="false"
												@change="getEventTypeList"
											>
												<el-option
													v-for="item in deviceModelList"
													:key="item.id"
													:value="item.id"
													:label="item.deviceModelName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="原因" prop="eventTypeId">
											<el-select v-model="state.queryForm.eventTypeId" clearable filterable placeholder="请选择报警原因" :teleported="false">
												<el-option
													v-for="item in eventTypeList"
													:key="item.id"
													:value="item.id"
													:label="item.eventTypeName"
													:disabled="item.state === 10"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="安装点" prop="installLocationId">
											<el-select v-model="state.queryForm.installLocationId" filterable placeholder="请选择" :teleported="false">
												<el-option v-for="item in buildingOptions" :key="item.id" :label="item.address" :value="item.id" />
											</el-select>
										</el-form-item>
									</el-col>

									<!-- <el-col :span="12" class="mb20">
										<el-form-item label="状态" prop="stocks">
											<el-select clearable v-model="state.queryForm.stocks" :teleported="false">
												<el-option label="全部" :value="20" />
												<el-option label="已处理" :value="10" />
												<el-option label="未处理" :value="10" />
											</el-select>
										</el-form-item>
									</el-col> -->
									<el-col :span="12" class="mb20">
										<el-form-item label="状态" prop="state">
											<el-select clearable v-model="state.queryForm.state" :teleported="false">
												<el-option label="已处理" :value="10" />
												<el-option label="未处理" :value="20" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="绑定状态" prop="bindState">
											<el-select clearable v-model="state.queryForm.bindState" :teleported="false">
												<el-option label="未绑定" :value="20" />
												<el-option label="已绑定" :value="30" />
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>

							<template #reference>
								<el-button link type="primary"
									>高级搜索<el-icon><ArrowDown /></el-icon>
								</el-button>
							</template>
						</el-popover>
						<el-input placeholder="请输入IMEI号" v-model="state.queryForm.imei" @keyup.enter="getDataList" />
						<el-button type="primary" @click="getDataList(true)">搜索</el-button>
						<el-button icon="refresh" @click="resetQuery()"></el-button>
					</el-space>
					<div>
						<el-button @click="exportExcel" v-auth="'platform_alarmFaultLogging_export'" v-if="false">导出记录</el-button>
					</div>
				</div>
			</el-row>
			<!-- <el-row>
				<div class="mb8" style="width: 100%">
					<el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()" v-auth="'platform_alarmFaultLogging_add'">
						新 增
					</el-button>
					<el-button
						plain
						:disabled="multiple"
						icon="Delete"
						type="primary"
						v-auth="'platform_alarmFaultLogging_del'"
						@click="handleDelete(selectObjs)"
					>
						删除
					</el-button>
					<right-toolbar
						v-model:showSearch="showSearch"
						:export="'platform_alarmFaultLogging_export'"
						@exportExcel="exportExcel"
						class="ml10 mr20"
						style="float: right"
						@queryTable="getDataList"
					></right-toolbar>
				</div>
			</el-row> -->
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
			>
				<el-table-column type="index" label="序号" width="60" />
				<!-- <el-table-column prop="deviceId" label="设备ID" show-overflow-tooltip /> -->
				<el-table-column prop="imei" label="IMEI" show-overflow-tooltip min-width="160">
					<template #default="{ row }">
						<div class="flex justify-start">
							<el-button icon="DocumentCopy" link type="primary" size="small" @click="copyText(row.imei)"></el-button>
							<el-button type="primary" link @click="handleDetail(row.deviceId, row.id)" size="small">{{ row.imei }}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="deviceTypeName" label="类型-型号" show-overflow-tooltip width="220">
					<template #default="{ row }">
						<span>
							{{ row.deviceTypeName }}
							-
							{{ row.deviceModelName }}
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="address" label="安装点" show-overflow-tooltip min-width="150" />
				<el-table-column prop="eventTypeName" label="故障原因" show-overflow-tooltip min-width="150" />
				<el-table-column prop="alarmCauses" label="故障内容" show-overflow-tooltip min-width="180" />
				<el-table-column prop="deptName" label="所属单位" show-overflow-tooltip width="220" />
				<el-table-column prop="createTime" label="故障时间" show-overflow-tooltip width="220" />
				<el-table-column prop="smsAlarmSketch" label="短信通知" :show-overflow-tooltip="{ popperClass: 'max-w-[280px]' }" min-width="150">
					<template #default="{ row }">
						<div>
							<el-button link type="primary" @click="notificationDialogRef.openDialog(row.smsAlarmId, '短信')">{{ row.smsAlarmSketch }}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="telephoneAlarmSketch" label="电话通知" :show-overflow-tooltip="{ popperClass: 'max-w-[280px]' }" min-width="150">
					<template #default="{ row }">
						<div>
							<el-button link type="primary" @click="notificationDialogRef.openDialog(row.telephoneAlarmId, '电话')">{{
								row.telephoneAlarmSketch
							}}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column
					prop="officialAccountAlarmSketch"
					label="公众号通知"
					:show-overflow-tooltip="{ popperClass: 'max-w-[280px]' }"
					min-width="150"
				>
					<template #default="{ row }">
						<div>
							<el-button link type="primary" @click="notificationDialogRef.openDialog(row.officialAccountAlarmId, '公众号')">{{
								row.officialAccountAlarmSketch
							}}</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="processingTime" label="处理时间" show-overflow-tooltip width="220" />
				<el-table-column prop="remarks" label="备注" show-overflow-tooltip min-width="120" />
				<el-table-column label="操作" width="80" fixed="right">
					<template #default="scope">
						<!-- <el-button icon="edit-pen" text type="primary" v-auth="'platform_alarmFaultLogging_edit'" @click="formDialogRef.openDialog(scope.row.id)"
							>编辑</el-button
						>
						<el-button icon="delete" text type="primary" v-auth="'platform_alarmFaultLogging_del'" @click="handleDelete([scope.row.id])"
							>删除</el-button
						> -->
						<el-button type="primary" @click="faultHandlingDialogRef.openDialog(scope.row.id)" size="small" v-if="scope.row.state !== 10"
							>处理</el-button
						>
						<el-button type="primary" link @click="handleDetail(scope.row.deviceId, scope.row.id)" size="small" v-else>查看详情</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
		<!-- 故障处理 -->
		<fault-handling-dialog ref="faultHandlingDialogRef" @refresh="getDataList(false)" />
		<!-- 通知记录 -->
		<notification-dialog ref="notificationDialogRef" />
	</div>
</template>

<script setup lang="ts" name="systemAlarmFaultLogging">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs } from '/@/api/alarm/alarmFaultLogging';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { deptTree } from '/@/api/admin/dept';
import { fetchListAll } from '/@/api/platform/basicDeviceType';
import { fetchListAll as fetchAllModelList } from '/@/api/platform/basicDeviceModel';
import { fetchListAll as fetchInstallListAll } from '/@/api/installation/basicInstallLocation';
import { fetchListAll as fetchEventTypeListAll } from '/@/api/alarm/alarmEventType';
import { useRouter } from 'vue-router';
import commonFunction from '/@/utils/commonFunction';
const router = useRouter();
const { copyText } = commonFunction();

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const FaultHandlingDialog = defineAsyncComponent(() => import('./components/faultHandling.vue'));
const notificationDialog = defineAsyncComponent(() => import('./components/notification.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
const faultHandlingDialogRef = ref();
const notificationDialogRef = ref();
const parentData: any = ref([]);
const deviceTypeList: any = ref([]);
const deviceModelList: any = ref([]);
const eventTypeList: any = ref([]);
const buildingOptions = ref<any[]>([]);
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	descs: ['create_time'],
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	state.queryForm.imei = '';
	getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/platform/alarmFaultLogging/export', Object.assign(state.queryForm, { ids: selectObjs }), '故障记录.xlsx');
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('此操作将永久删除');
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
getDeptData();
// 获取设备数据
const getDeviceTypes = () => {
	fetchListAll({ state: 10 }).then((res) => {
		deviceTypeList.value = res.data;
	});
};
getDeviceTypes();
// 查询设备型号
const getModelList = (deviceTypeId: string) => {
	state.queryForm.deviceModelId = null;
	fetchAllModelList({ deviceTypeId, state: 10 }).then((res) => {
		deviceModelList.value = res.data;
	});
	// fetchEventTypeListAll({ deviceTypeId, state: 20 }).then((res) => {
	// 	eventTypeList.value = res.data;
	// });
};
// 查询事件类型
const getEventTypeList = (deviceModelId: string) => {
	state.queryForm.eventTypeId = null;
	fetchEventTypeListAll({ deviceModelId, state: 20, deviceTypeId: state.queryForm.deviceTypeId }).then((res) => {
		eventTypeList.value = res.data.filter((d: { alarmTypeCode: string }) => {
			return d.alarmTypeCode === 'FAULT_ALARM' || d.alarmTypeCode === 'TIMEOUT';
		});
	});
};
const getBuildings = () => {
	fetchInstallListAll().then((res) => {
		buildingOptions.value = res.data;
	});
};
getBuildings();
const handleDetail = (id: string, fid: string) => {
	router.push({ path: '/platform/basicDevice/facilityDetails', query: { id, type: '2', fid } });
};
</script>
